package tech.dongliang.common.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import tech.dongliang.common.enums.EBizError;
import tech.dongliang.common.exception.BizException;

import java.util.stream.Collectors;

@Component
@Aspect
@Slf4j
public class ControllerValidateAspect {


    /**
     * 拦截注解为springController的*Mapping并且最后一个参数为BindingResult的方法
     * 判断BindingResult结果，验证有错误，直接抛出异常
     *
     * @param joinPoint
     */
    @Before("execution(@org.springframework.web.bind.annotation.*Mapping * *..*.*(..,org.springframework.validation.BindingResult))")
    public void beforeDebugTraceMethod(JoinPoint joinPoint) throws BizException {
        Object[] paramValues = joinPoint.getArgs();
        BindingResult result = null;
        for (int i = 0; i < paramValues.length; i++) {
            if (paramValues[i] instanceof BindingResult) {
                result = (BindingResult) paramValues[i];
                break;
            }
        }
        if (result.hasErrors()) {
            String errMsg = result.getAllErrors().parallelStream().map(msg -> msg.getDefaultMessage()).collect(Collectors.joining(","));
            throw new BizException(EBizError.PARAMETER_VALIDATION_ERROR, errMsg);
        }
    }
}
